package com.jie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jie.dao.CartDao;
import com.jie.entity.ShoppingCart;
import com.jie.service.ShoppingCartService;
import com.jie.service.impl.ShoppingCartServiceImpl;
import com.jie.utility.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jie
 * @since 2024-03-15
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService cartService;
    @PostMapping("/addCart")
    public R<String> addCart(@RequestBody ShoppingCart shoppingCart){
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getGoodsId,shoppingCart.getGoodsId());
        queryWrapper.eq(ShoppingCart::getManyAttrsIndex,shoppingCart.getManyAttrsIndex());

        ShoppingCart one = cartService.getOne(queryWrapper);
        if(one!=null){
           int a=  one.getNumber()+shoppingCart.getNumber();
           one.setNumber(a);
            boolean b = cartService.updateById(one);
            if(b)return R.success("添加到购物车");
            return R.error("添加购物车失败");
        }else {
            boolean save = cartService.save(shoppingCart);
            if(save)return R.success("添加到购物车");
            return R.error("添加购物车失败");
        }

    }
    @GetMapping("/allCart")
    public R<List<CartDao>> allCart(ShoppingCart shoppingCart){
        List<CartDao> cartDaos = cartService.allCart(shoppingCart.getUserId());
        return R.success(cartDaos);
    }
    @PutMapping("/editCart")
    public R<String> editCart(@RequestBody ShoppingCart shoppingCart){
        boolean b = cartService.updateById(shoppingCart);
        if(b) return R.success("修改购物车商品成功！");
        return R.error("修改购物车商品失败!");
    }
    @DeleteMapping("/delCart")
    public R<String> delCart(int id){
        boolean b = cartService.removeById(id);
        if(b)return R.success("删除购物车成功！");
        return   R.error("删除购物车失败！");
    }

}

